package Import::Admin;

use utf8;

BEGIN
{
	push @INC, './Import';
}

use XML::LibXML;
use Datasource;

my $MAX = 50;

return new();

sub new
{
	my $class = shift;
	my $this = {'add-new' => \&addNew,
		'keyword-list' => \&keywordList,
		'edit-message' => \&editMessage,
		'message-list' => \&messageList};
	return bless $this, $class;
}

sub addNew
{
	my $page = shift;
	my $node = shift;
	my $args = shift;

	if ($page->param ('submit') && $page->param ('title') && $page->param ('ContentField'))
	{
		my $message_id = addMessage ($page);
		tieKeywords ($page, $message_id);
		
		print "Location: http://$ENV{'SERVER_NAME'}/preview/$message_id/\n\n";
		exit;
	}

	return $node;
}

sub keywordList
{
	my $page = shift;
	my $node = shift;
	my $args = shift;
	my $dbh = $Datasource::handler;

	my $sth = $dbh->prepare ("select keyword, uri from keywords order by keyword");
	$sth->execute();
	while (my ($keyword, $uri) = $sth->fetchrow_array())
	{
		my $item = $page->{'xml'}->createElement ('item');
		$item->appendText ($keyword);
		$item->setAttribute ('uri', $uri);
		$node->appendChild ($item);
	}

	return $node;
}

sub editMessage
{
	my $page = shift;
	my $node = shift;
	my $args = shift;
	my $dbh = $Datasource::handler;

	my ($message_id) = $page->param ('message_id') =~ /(\d+)/;

	if ($message_id)
	{
		if ($page->param ('submit') && $page->param ('title') && $page->param ('ContentField'))
		{
			updateMessage ($page, $message_id);
			tieKeywords ($page, $message_id);
		}
		
		my $sth = $dbh->prepare ("select uri, title, content, is_published, site_id, dayofmonth(date), month(date), year(date), hour(date), minute(date) from message where id = $message_id");
		$sth->execute();
		my ($uri, $title, $content, $is_published, $site_id, $day, $month, $year, $hour, $minute) = $sth->fetchrow_array();
		$sth->finish();
		
		my $titleNode = $page->{'xml'}->createElement ('title');
		$titleNode->appendText ($title);
		$titleNode->setAttribute ('uri', $uri); 
		$titleNode->setAttribute ('site_id', $site_id); 
		$titleNode->setAttribute ('is_published', $is_published);
		$titleNode->setAttribute ('day', $day);
		$titleNode->setAttribute ('month', $month);
		$titleNode->setAttribute ('year', $year);
		$titleNode->setAttribute ('hour', $hour);
		$titleNode->setAttribute ('minute', $minute);
		$node->appendChild ($titleNode);

		my $contentNode = $page->{'xml'}->createElement ('content');
		$contentNode->appendText ($content);
		$node->appendChild ($contentNode);


		my $keywords = $page->{'xml'}->createElement ('keywords');
		$node->appendChild ($keywords);

		$sth = $dbh->prepare ("select keyword, uri from keywords join keyword2message on keywords.id = keyword2message.keyword_id where message_id = $message_id order by keyword2message.id");
		$sth->execute();
		while (my ($keyword, $keyword_uri) = $sth->fetchrow_array())
		{
			my $item = $page->{'xml'}->createElement ('item');
			$item->appendText ($keyword);
			$item->setAttribute ('uri', $keyword_uri);
			$keywords->appendChild ($item)
		}
		$sth->finish();
	}

	return $node;
}

sub messageList
{
	my $page = shift;
	my $node = shift;
	my $args = shift;
	my $dbh = $Datasource::handler;

	my $sth = $dbh->prepare ("select id, dayofmonth(date), month(date), year(date), hour(date), minute(date), date <= now(), title, is_published, site_id from message order by date desc, id desc");
	$sth->execute();
	while (my ($id, $day, $month, $year, $hour, $minute, $is_visible, $title, $is_published, $site_id) = $sth->fetchrow_array())
	{
		my $item = $page->{'xml'}->createElement ('item');
		$item->setAttribute ('id', $id);
		$item->setAttribute ('day', $day);
		$item->setAttribute ('month', $month);
		$item->setAttribute ('year', $year);
		$item->setAttribute ('hour', $hour);
		$item->setAttribute ('minute', $minute);
		$item->setAttribute ('is_visible', $is_visible);
		$item->setAttribute ('is_published', $is_published);
		$item->setAttribute ('site_id', $site_id);
		$item->appendText ($title);
		$node->appendChild ($item);
	}
	$sth->finish();

	return $node;
}

sub addMessage
{
	my $page = shift;
	my $dbh = $Datasource::handler;

	my $uri = $page->param ('uri');
	$uri = random_uri() unless $uri;

	my ($site_id) = $page->param ('site_id') =~ m{(\d)};
	$site_id = 1 unless $site_id;

	$dbh->do (
			"insert into message (title, content, uri, is_published, date, site_id) values (" .
			$dbh->quote ($page->param ('title')) . ", " .
			$dbh->quote ($page->param ('ContentField')). ", " .
			$dbh->quote ($uri). ", " .
			"0, now(), " .
			$site_id . ")"
	);

	my $sth = $dbh->prepare ("select last_insert_id() from message");
	$sth->execute();
	my ($message_id) = $sth->fetchrow_array();
	$sth->finish();

	return $message_id;
}

sub updateMessage
{
	my $page = shift;
	my $message_id = shift;
	my $dbh = $Datasource::handler;

	my $is_published = defined $page->param ('is_published') ? 1 : 0;

	my $uri = $page->param ('uri');
	$uri = random_uri() unless $uri;

	my ($site_id) = $page->param ('site_id') =~ m{(\d)};
	$site_id = 1 unless $site_id;

	my ($day) = $page->param ('day') =~ m{(\d+)};
	my ($month) = $page->param ('month') =~ m{(\d+)};
	my ($year) = $page->param ('year') =~ m{(\d+)};
	my ($hour) = $page->param ('hour') =~ m{(\d+)};
	my ($minute) = $page->param ('minute') =~ m{(\d+)};

	$dbh->do (
			"update message " .
			"set title = " . $dbh->quote ($page->param ('title')) . ", ".
			"content = " . $dbh->quote ($page->param ('ContentField')) . ", ".
			"uri = " . $dbh->quote ($uri) . ", ".
			"is_published = $is_published, ".
			"site_id = $site_id, ".
			"date = '${year}-${month}-${day} ${hour}:${minute}' ".
			"where id = $message_id");
		
	return $message_id;
}

sub tieKeywords
{
	my $page = shift;
	my $message_id = shift;
	my $dbh = $Datasource::handler;

	my @keywords = split /\s*,\s*/, $page->param ('keywords');
	return unless @keywords;

	$dbh->do ("delete from keyword2message where message_id = $message_id");
	foreach my $keyword (@keywords)
	{
		$keyword =~ s{^\s+}{};
		$keyword =~ s{\s+$}{};
		$keyword =~ s{"}{\\\"}g;   #"

#		my $sth = $dbh->prepare ("select count(*) from keywords where keyword=\"$keyword\"");
		my $sth = $dbh->prepare ("select count(*) from keywords where uri=\"$keyword\"");
		$sth->execute();
		my ($count) = $sth->fetchrow_array();
		$sth->finish();

		unless ($count)
		{
			my $uri = transliterate ($keyword);
			$dbh->do ("insert into keywords (keyword, uri) values (\"$keyword\", \"$uri\")");
		}

#		$sth = $dbh->prepare ("select id from keywords where keyword=\"$keyword\"");
		$sth = $dbh->prepare ("select id from keywords where uri=\"$keyword\"");
		$sth->execute();
		my ($keyword_id) = $sth->fetchrow_array();
		$sth->finish();	

		$dbh->do ("insert into keyword2message (keyword_id, message_id) values ($keyword_id, $message_id)");
	}
}

sub random_uri
{
	my @chars = ('a'..'z', '0'..'9');
	my $uri = join ('', @chars[map{rand @chars}(1..20)]);
	return $uri;
}

sub transliterate
{
	 my $name = shift;

#	 $name =~ tr /абвгдезийклмнопрстуфхыэ/abvgdeziyklmnoprstufhye/;
#	 $name =~ tr /АБВГДЕЗИЙКЛМНОПРСТУФХЫЭ/ABVGDEZIYKLMNOPRSTUFHYE/;

	 $name =~ s/ё/yo/g;
	 $name =~ s/ж/zh/g;
	 $name =~ s/ц/ts/g;
	 $name =~ s/ч/ch/g;
	 $name =~ s/ш/sh/g;
	 $name =~ s/щ/sch/g;
	 $name =~ s/ю/yu/g;
	 $name =~ s/я/ya/g;

	 $name =~ s/Ё/YO/g;
	 $name =~ s/Ж/ZH/g;
	 $name =~ s/Ц/TS/g;
	 $name =~ s/Ч/CH/g;
	 $name =~ s/Ш/SH/g;
	 $name =~ s/Щ/SCH/g;
	 $name =~ s/Ю/YU/g;
	 $name =~ s/Я/YA/g;

	 $name =~ s/ /-/g;
	 $name =~ s/\@/a/g;
#	 $name = lc ($name);
#	 $name =~ s{[^-_0-9a-z]}{}g;

	 return $name;
}

1;		
